package com.weidong.mybbs.service;

import com.weidong.mybbs.entity.SysUser;
import com.weidong.mybbs.exception.BusinessException;
import com.weidong.mybbs.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

@Service
public class AuthService {

    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private SysUserMapper sysUserMapper;

    private static final String SESSION_ID_REDIS_KEY = "Auth:Session-ID:%s";

    private static final String SESSION_ID_HEADER_KEY = "WD-Session-ID";

    public Cookie login(String username,String password,String clientIp,boolean rememberMe){
        //验证数据
        if (StringUtils.isBlank(username)){
            throw new BusinessException("用户名不能为空");
        }

        if (StringUtils.isBlank(password)){
            throw new BusinessException("密码输入有误");
        }

        if (StringUtils.isBlank(clientIp)){
            throw new BusinessException("上网环境有问题");
        }

        //查询用户
        SysUser sysUser = sysUserMapper.findByName(username);
        if (sysUser == null){
            throw new BusinessException("用户名不存在");
        }

        if (!BCrypt.checkpw(password,sysUser.getPassword())){
            throw new BusinessException("密码不正确");
        }
        Date now = new Date();
        sysUser.setLoginDate(now);
        sysUser.setLoginIp(clientIp);
        sysUserMapper.updateById(sysUser);
        String sessionId = UUID.randomUUID().toString();
        try (Jedis jedis = jedisPool.getResource()){
            //构建redis key
            String key = String.format(SESSION_ID_REDIS_KEY,sessionId);
            jedis.setex(key,7200,String.valueOf(sysUser.getUserId()));
        }

        Cookie cookie = new Cookie(SESSION_ID_HEADER_KEY,sessionId);
        cookie.setPath("/");
        cookie.setMaxAge(7200);
        return cookie;
    }

    /**
     * 获取sessionID
     * @param request request
     * @return
     */
    public String getSessionId(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie c:cookies) {
                if (c.getName().toLowerCase().equals(SESSION_ID_HEADER_KEY.toLowerCase())){
                    return StringUtils.trimToNull(c.getValue());
                }
            }
        }
        return null;
    }

    public SysUser getCurrentUser(HttpServletRequest request){
        String sessionId = getSessionId(request);
        if (StringUtils.isBlank(sessionId)){
            throw new BusinessException("sessionId未获取到");
        }

        if (!validLogin(sessionId)){
            throw new BusinessException("未登录");
        }

        try (Jedis jedis = jedisPool.getResource()){
            //构建redis key
            String key = String.format(SESSION_ID_REDIS_KEY,sessionId);
            if (jedis.exists(key)){
                int userId = Integer.valueOf(jedis.get(key));
                SysUser sysUser =  sysUserMapper.findById(userId);
                if (sysUser == null){
                    throw new BusinessException("用户未找到");
                }
                return sysUser;
            }
        }
        throw new BusinessException("用户未找到");
    }

    /**
     * 验证登陆
     * @param sessionId
     * @return
     */
    public boolean validLogin(String sessionId){
        try (Jedis jedis = jedisPool.getResource()){
            //构建redis key
            String key = String.format(SESSION_ID_REDIS_KEY,sessionId);
            if (jedis.exists(key)){
                return StringUtils.isNotBlank(jedis.get(key));
            }
        }
        return false;
    }

    /**
     * 生成session
     * @return
     */
    public Cookie generateSession(){
        String sessionId = UUID.randomUUID().toString();
        try (Jedis jedis = jedisPool.getResource()){
            //构建redis key
            String key = String.format(SESSION_ID_REDIS_KEY,sessionId);
            jedis.setex(key,7200,"");
        }

        Cookie cookie = new Cookie(SESSION_ID_HEADER_KEY,sessionId);
        cookie.setPath("/");
        cookie.setMaxAge(7200);
        return cookie;
    }
}
